/***************************************************************************
 *   Copyright (C) 2008 by BogDan Vatra                                    *
 *   bogdan@licentia.eu                                                    *
 *                                                                         *
 *   This program is free software: you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation, either version 3 of the License, or     *
 *   (at your option) any later version.                                   *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>. *
 ***************************************************************************/
#include <QCloseEvent>
#include <QShowEvent>
#include <QDesktopWidget>

#include "kontamabilwindow.h"

KontAMabilWindow::KontAMabilWindow(QWidget* parent, Qt::WFlags fl)
		: QWidget(parent, fl),m_eventLoop(0)
{
	setWindowModality(Qt::ApplicationModal);
}

KontAMabilWindow::~KontAMabilWindow()
{
	delete m_eventLoop;
}

void KontAMabilWindow::showEvent(QShowEvent * event)
{
	QWidget::showEvent(event);
	if (event->isAccepted())
	{
		QDesktopWidget w;
		QRect rect = w.screenGeometry(this);
		move(rect.width() / 2 - frameGeometry().width() / 2, rect.height() / 2 - frameGeometry().height() / 2);
		emit(aboutToShow());
	}
}

int KontAMabilWindow::exec()
{
	setWindowFlags(windowFlags()|QFlag(Qt::Dialog));
	show();
	delete m_eventLoop;
	m_eventLoop= new QEventLoop;
	return m_eventLoop->exec();
}


void KontAMabilWindow::closeEvent(QCloseEvent * event)
{
	if (m_eventLoop && m_eventLoop->isRunning())
		m_eventLoop->exit(false);
	QWidget::closeEvent(event);
	if (event->isAccepted())
		emit(aboutToClose());
}

void KontAMabilWindow::accept()
{
	emit(aboutToAccept());
	if (m_eventLoop)
		m_eventLoop->exit(true);
	close();
}

void KontAMabilWindow::reject()
{
	emit(aboutToReject());
	if (m_eventLoop)
		m_eventLoop->exit(false);
	close();
}
